#!/bin/bash

function usage {
  echo "Usage: $0 <from> <to>"
  echo -e "\nBoth <from> and <to> must be valid PicasaFS mounts, already mounted"
  echo -e "\nThis script will copy all photos and their metadata"
  echo "Copyright 2008 Håvard Gulldahl <havard@gulldahl.no>, GPLv2 licensed"
  exit 1;
}

OLDTREE=$1;
shift;
NEWTREE=$1;
shift;

test "$OLDTREE" || usage;
test "$NEWTREE" || usage;
DEBUG=1;

function debug {
  test "${DEBUG}" && echo DEBUG: $*;
}

function error {
  echo ERROR: $*;
  exit 99;
}

for OLDALBUM in "$OLDTREE"/Giftemålsplass;
do
  ALBUM=$(basename "${OLDALBUM}");
  echo Copying album \"${ALBUM}\";
  NEWALBUM="${NEWTREE}/${ALBUM}";
  debug ... that is, ${OLDALBUM} is migrated to ${NEWALBUM}...;
  test -d "${NEWALBUM}" || mkdir "${NEWALBUM}"
  sleep 3;
  test -d "${NEWALBUM}" || error "Could not create album: $NEWALBUM";
  echo .. Going to copy $(ls "$OLDALBUM" | wc -l) photos;
  for OLDPHOTO in "${OLDALBUM}"/*;
  do
    PHOTO=$(basename "${OLDPHOTO}");
    NEWPHOTO="$NEWALBUM"/$PHOTO;
    test -d "$NEWPHOTO" && continue; ## photo exists / is already copied
    echo .... ${PHOTO};
    cp -v "$OLDPHOTO"/original.jpg "$NEWPHOTO" && echo ...... Photo copied: $PHOTO;
#     sleep 2; # don't confuse picasafs
  done;
  sleep 3; ## Wait for update
  for OLDPHOTO in "${OLDALBUM}"/*;
  do
    PHOTO=$(basename "${OLDPHOTO}");
    NEWPHOTO="$NEWALBUM"/$PHOTO;
  
    #### COMMENTS ####
    COMMENTS=$(( $(ls "$OLDPHOTO"/COMMENTS | wc -l ) ));
    echo ...... There are $COMMENTS comments to copy;
    if [ $COMMENTS -gt 0 ];
    then
      for OLDCOM in "$OLDPHOTO"/COMMENTS/*;
      do
        COMMENT=$(basename "$OLDCOM");
        NAME=$(basename $COMMENT .txt | cut --fields=2- --delimiter=_ | sed s/_//g);
        echo ...... "$COMMENT";
        cat "$OLDCOM" > /tmp/"$COMMENT.txt";
        echo -e "\n\n-- \nOriginally written by $NAME, imported here $(date)" >> /tmp/"$COMMENT.txt";
        cp /tmp/"$COMMENT.txt" "$NEWPHOTO"/COMMENTS/"$COMMENT.txt" && echo ........ Comment copied: $COMMENT;
#         sleep 2;
      done
    fi  
    #### METADATA ####
    # Doing it lastly, since it will may some file names
    echo ...... Copying metadata for image: ${PHOTO};
    debug $OLDPHOTO/info.txt -\> $NEWPHOTO/info.txt
    cp "$OLDPHOTO"/info.txt "$NEWPHOTO"/info.txt && echo "........ done";
#     sleep 2;

  done

done

echo "Migration finished!"